// 模拟接口：知识库管理

// 模拟数据存储
let categories = [
  {
    id: 1,
    label: '土建工程',
    children: [
      { id: 11, label: '结构' },
      { id: 12, label: '基础' },
      { id: 13, label: '主体' }
    ]
  },
  {
    id: 2,
    label: '机电工程',
    children: [
      { id: 21, label: '给排水' },
      { id: 22, label: '暖通' },
      { id: 23, label: '电气' },
      { id: 24, label: '弱电' },
      { id: 25, label: '消防' }
    ]
  },
  {
    id: 3,
    label: '装修工程',
    children: [
      { id: 31, label: '内装' },
      { id: 32, label: '外装' },
      { id: 33, label: '特殊装修' }
    ]
  },
  {
    id: 4,
    label: '市政工程',
    children: [
      { id: 41, label: '道路' },
      { id: 42, label: '桥梁' },
      { id: 43, label: '管网' },
      { id: 44, label: '园林' }
    ]
  }
];

let knowledgeItems = [
  {
    id: 1,
    title: '基础施工规范',
    type: '文本',
    importance: '关键',
    updateTime: '2024-01-20 10:00:00',
    content: '基础施工的标准流程和注意事项...',
    tags: ['施工规范', '基础工程'],
    categoryId: 12
  }
];

let nextCategoryId = 5;
let nextKnowledgeId = 2;

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 添加分类
export function addCategory(categoryData) {
  return new Promise(async (resolve, reject) => {
    await delay(500); // 模拟网络请求延迟
    
    if (!categoryData.name) {
      reject("分类名称不能为空");
      return;
    }
    
    const newCategory = {
      id: nextCategoryId++,
      label: categoryData.name,
      children: []
    };
    
    // 如果有父级分类，则添加到父级分类中
    if (categoryData.parent) {
      const parentId = categoryData.parent;
      const findAndAdd = (cats) => {
        for (let cat of cats) {
          if (cat.id === parentId) {
            cat.children = cat.children || [];
            cat.children.push(newCategory);
            return true;
          }
          if (cat.children && findAndAdd(cat.children)) {
            return true;
          }
        }
        return false;
      };
      
      if (!findAndAdd(categories)) {
        reject("父级分类不存在");
        return;
      }
    } else {
      // 添加为顶级分类
      categories.push(newCategory);
    }
    
    resolve(newCategory);
  });
}

// 添加知识
export function addKnowledge(knowledgeData) {
  return new Promise(async (resolve, reject) => {
    await delay(500); // 模拟网络请求延迟
    
    if (!knowledgeData.title) {
      reject("知识标题不能为空");
      return;
    }
    
    if (!knowledgeData.categoryId) {
      reject("请选择分类");
      return;
    }
    
    const newKnowledge = {
      id: nextKnowledgeId++,
      title: knowledgeData.title,
      type: knowledgeData.type || 'text',
      importance: knowledgeData.importance || '一般',
      content: knowledgeData.content || '',
      tags: knowledgeData.tags || [],
      updateTime: new Date().toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit', 
        hour: '2-digit', 
        minute: '2-digit', 
        second: '2-digit' 
      }).replace(/\//g, '-'),
      categoryId: knowledgeData.categoryId
    };
    
    knowledgeItems.push(newKnowledge);
    resolve(newKnowledge);
  });
}

// 获取所有分类
export function getCategories() {
  return new Promise(async (resolve) => {
    await delay(300); // 模拟网络请求延迟
    resolve(JSON.parse(JSON.stringify(categories))); // 返回深拷贝数据
  });
}

// 获取所有知识
export function getKnowledge() {
  return new Promise(async (resolve) => {
    await delay(300); // 模拟网络请求延迟
    resolve(JSON.parse(JSON.stringify(knowledgeItems))); // 返回深拷贝数据
  });
}

// 根据分类ID获取知识
export function getKnowledgeByCategory(categoryId) {
  return new Promise(async (resolve) => {
    await delay(300); // 模拟网络请求延迟
    if (!categoryId) {
      resolve(JSON.parse(JSON.stringify(knowledgeItems)));
    } else {
      const filtered = knowledgeItems.filter(item => item.categoryId === categoryId);
      resolve(JSON.parse(JSON.stringify(filtered)));
    }
  });
}

// 编辑分类
export function editCategory(categoryData) {
  return new Promise(async (resolve, reject) => {
    await delay(500);
    
    if (!categoryData.id) {
      reject("分类ID不能为空");
      return;
    }
    
    if (!categoryData.name) {
      reject("分类名称不能为空");
      return;
    }
    
    const findAndUpdate = (cats) => {
      for (let cat of cats) {
        if (cat.id === categoryData.id) {
          cat.label = categoryData.name;
          return true;
        }
        if (cat.children && findAndUpdate(cat.children)) {
          return true;
        }
      }
      return false;
    };
    
    if (findAndUpdate(categories)) {
      resolve({ message: "更新成功" });
    } else {
      reject("分类不存在");
    }
  });
}

// 删除分类
export function deleteCategory(categoryId) {
  return new Promise(async (resolve, reject) => {
    await delay(500);
    
    if (!categoryId) {
      reject("分类ID不能为空");
      return;
    }
    
    // 查找要删除的分类及其所有子分类
    const findAllCategoryIds = (cats) => {
      let ids = [];
      cats.forEach(cat => {
        ids.push(cat.id);
        if (cat.children && cat.children.length > 0) {
          ids = ids.concat(findAllCategoryIds(cat.children));
        }
      });
      return ids;
    };
    
    const findAndDelete = (cats) => {
      for (let i = 0; i < cats.length; i++) {
        if (cats[i].id === categoryId) {
          // 找到要删除的分类，获取该分类及其所有子分类的ID
          const allCategoryIds = findAllCategoryIds([cats[i]]);
          // 删除该分类下的所有知识
          knowledgeItems = knowledgeItems.filter(item => !allCategoryIds.includes(item.categoryId));
          // 删除该分类
          cats.splice(i, 1);
          return true;
        }
        if (cats[i].children && findAndDelete(cats[i].children)) {
          return true;
        }
      }
      return false;
    };
    
    if (findAndDelete(categories)) {
      resolve({ message: "删除成功" });
    } else {
      reject("分类不存在");
    }
  });
}

// 删除知识
export function deleteKnowledge(knowledgeId) {
  return new Promise(async (resolve, reject) => {
    await delay(500);
    
    if (!knowledgeId) {
      reject("知识ID不能为空");
      return;
    }
    
    const index = knowledgeItems.findIndex(item => item.id === knowledgeId);
    if (index > -1) {
      knowledgeItems.splice(index, 1);
      resolve({ message: "删除成功" });
    } else {
      reject("知识不存在");
    }
  });
}